const tbody = document.querySelector('tbody')

// 获取成绩
const getScore = async () => render((await axiosFn('/score/list')).data.data)
getScore()

// 渲染函数
function render(list) {
  const arr = []
  for (const key in list) {
    arr.push({ id: key, name: list[key].name, group: list[key].group, score: list[key].score })
  }

  tbody.innerHTML = arr
    .map(
      item => `
  <tr>
    <th scope="row" >${item.id}</th>
    <td>${item.name}</td>
    <td class="score" data-stu_id=${item.id} data-batch=1 data-score=${item.score[0]}>${item.score[0]}</td>
    <td class="score" data-stu_id=${item.id} data-batch=2 data-score=${item.score[1]}>${item.score[1]}</td>
    <td class="score" data-stu_id=${item.id} data-batch=3 data-score=${item.score[2]}>${item.score[2]}</td>
    <td class="score" data-stu_id=${item.id} data-batch=4 data-score=${item.score[3]}>${item.score[3]}</td>
    <td class="score" data-stu_id=${item.id} data-batch=5 data-score=${item.score[4]}>${item.score[4]}</td>
  </tr>  `
    )
    .join('')
}

// 双击修改成绩
tbody.addEventListener('dblclick', e => {
  const element = e.target
  const { stu_id, batch, score } = e.target.dataset
  if (score === element.textContent) {
    // 创造input输入框
    element.innerHTML = `<input type='text' value=${score} style=display:block>`
    // 设置输入框
    const input = element.firstChild
    // 获取焦点
    input.focus()
    // 光标定位到末端 setSelectionRange 选中input框的一段文本 参数(光标起始位置,光标结束位置)
    input.setSelectionRange(input.value.length, input.value.length)
    // 修改成绩函数
    async function editScore() {
      if (input.value < 0 || input.value > 100) toastr.error('成绩范围应是 0~100 ', '成绩范围有误')
      else await axiosFn('/score/entry', 'post', { stu_id, batch, score: input.value })
      getScore()
    }
    // 失去焦点
    input.addEventListener('blur', editScore)

    // 回车事件
    input.addEventListener('keyup', e => {
      if (e.key === 'Enter') {
        input.removeEventListener('blur', editScore)
        editScore()
      }
    })
  }
})
